import { dom } from "../tool";

interface PropType {
    value?: string | number | null;
    onChange?: (value: string | number | null | undefined) => void;
    disabled?: boolean;
    label?: string | HTMLElement;
    target?: HTMLElement;
    style?: string;
    inputStyle?: string;
}

interface InputType {
    new(props?: PropType): InputType;
    value: string | number | null | undefined;
    disabled: boolean;
    setValue: (value: string | number | null | undefined) => void;
    setDisabled: (disabled: boolean) => void;
    render: (node?: HTMLElement) => HTMLElement;
    onChange?: (value: string | number | null | undefined) => void;
}

function Input(this: InputType, props?: PropType) {
    const { value = '', onChange, disabled = false, label, target, style, inputStyle } = props || {};
    this.onChange = onChange;
    const node: any = dom('input', { className: 'gkh-input', target, style: label ? inputStyle : style });
    let container = node;
    if (label) {
        if (label instanceof Node) {
            container = dom('div', { className: 'gkh-form-item', target, style, childs: [dom('label', { child: label }), node] })
        } else {
            container = dom('div', { className: 'gkh-form-item', target, style, childs: [dom('label', { innerText: label }), node] })
        }
    }

    node.onchange = () => {
        this.value = node.value;
        if (this.onChange) {
            this.onChange(this.value);
        }
    }

    this.setValue = (arg) => {
        this.value = arg;
        node.value = arg;
    }

    this.setDisabled = (arg) => {
        this.disabled = arg;
        node.disabled = arg;
    }

    this.setDisabled(disabled);
    this.setValue(value);

    this.render = (arg) => {
        if (arg) {
            arg.appendChild(container);
        }
        return container;
    }

    return this;
}

export default Input as unknown as InputType;